var express = require('express');
var router = express.Router();

var axios = require('axios')

const { MaizuoUsersModel } = require('../utils/model')
const { createToken, checkToken } = require('../utils/token')


// 注册
router.post('/mzregister', function (req, res) {
    var body = req.body;
    // console.log(body, 111);
    MaizuoUsersModel.findOne({
        $or: [
            { username: body.username },
            { phone: body.phone }
        ]
    })
        .then(data => {
            if (data) {
                // console.log(data);
                if (body.phone == data.phone) {     
                    res.json({
                        code: 402,
                        result: null,
                        msg: '注册失败，手机号已被注册',
                        type: 0
                    })
                }
                if (body.username == data.username) {     
                    res.json({
                        code: 402,
                        result: null,
                        msg: '注册失败，用户名已存在',
                        type: 0
                    })
                }
            } else {
                // 注册
                body.time = new Date()
                body.avatar = 'public\\avatar\\default-avatar.png'
                MaizuoUsersModel.insertMany(body)
                    .then(result => {
                        // console.log(result);
                        if (result) {     
                            res.json({
                                code: 200,
                                result: null,
                                msg: '注册成功',
                                type: 1
                            })
                        }
                    })
            }
        })
})

// 登陆
router.post('/mzlogin', (req, res) => {
    var body = req.body;
    // console.log(body, 111);
    MaizuoUsersModel.findOne({
        username: body.username
    })
        .then(result => {
            console.log(result);
            if (result) {
                body.time = new Date();
                const token = createToken(body);
                if (body.password == result.password) {
                    res.json({
                        code: 200,
                        result,
                        msg: '登陆成功',
                        type: 1,
                        token
                    })
                } else {
                    res.json({
                        code: 402,
                        msg: '登陆失败，密码输入错误',
                        type: 0
                    })
                }
            } else {
                res.json({
                    code: 402,
                    result,
                    msg: '登陆失败，用户名不存在',
                    type: 0
                })
            }
        })
        .catch(err => {
            console.log(err);
            res.json({
                code: 500,
                err,
                msg: '服务器异常',
                type: 0
            })
        })
})

// 忘记密码，修改密码
router.post('/mzmodifypassword', (req, res) => {
    var body = req.body;
    console.log(body, 111);
    MaizuoUsersModel.updateMany({
        phone: body.phone
    }, {
        $set: {
            password: body.password
        }
    })
        .then(result => {
            console.log(result);
            if (result) {
                res.json({
                    code: 200,
                    result,
                    msg: '修改密码成功',
                    type: 1,
                })
            } 
        })
        .catch(err => {
            console.log(err);
            res.json({
                code: 500,
                err,
                msg: '服务器异常',
                type: 0
            })
        })
})

// 发送验证码
router.get('/mzsendcaptcha', (req, res) => {
    var { phone } = req.query;
    MaizuoUsersModel.findOne({
        phone
    })
        .then(data => {
            if (data) {
                // 发送验证码
                axios.get('http://47.104.209.44:3333/captcha/sent', {
                    params: {
                        phone
                    }
                })
                    .then(result => {
                        // console.log(result.data);
                        if (result.data.code == 200) {
                            res.json({
                                code: 200,
                                ...result.data,
                                msg: '验证码发送成功',
                                type: 1
                            })
                        }
                    })
            } else {
                res.json({
                    code: 402,
                    msg: '发送失败，手机号未注册',
                    type: 0
                })
            }
        })
        .catch(err => {
            console.log(err);
            res.json({
                code: 500,
                err,
                msg: '服务器异常',
                type: 0
            })
        })
})

// 校验验证码
router.get('/mzverifycaptcha', (req, res) => {
    var { phone, captcha } = req.query;
    MaizuoUsersModel.findOne({
        phone
    })
        .then(data => {
            console.log(data,000);
            if (data) {
                // 校验验证码
                axios.get('http://47.104.209.44:3333/captcha/verify', {
                    params: {
                        phone, captcha
                    }
                })
                    .then(result => {
                        console.log(result.data);
                        var token = createToken({ phone, time: new Date() })
                        if (result.data.code == 200) {
                            res.json({
                                code: 200,
                                ...result.data,
                                msg: '验证码校验成功',
                                type: 1,
                                token
                            })
                        }
                    })
                    .catch(err => {
                        console.log(err);
                        res.json({
                            code: 402,
                            msg: '验证码填写错误，请重新输入',
                            type: 0
                        })
                    })
            } else {
                res.json({
                    code: 402,
                    msg: '发送失败，手机号未注册',
                    type: 0
                })
            }
        })
        .catch(err => {
            console.log(err);
            res.json({
                code: 500,
                err,
                msg: '服务器异常',
                type: 0
            })
        })
})


// 获取个人信息
router.get('/mzgetuserinfo', (req, res) => {
    // var { telphone: phone, username } = req.query;
    checkToken(req, res, ({
        phone, username
    }) => {
        MaizuoUsersModel.findOne({
            $or: [
                { phone },
                { username }
            ]
        })
            .then(result => {
                // console.log(result);
                res.json({
                    code: 200,
                    msg: "个人信息获取成功",
                    type: 1,
                    result
                })
            })
            .catch(err => {
                console.log(err);
                res.json({
                    code: 500,
                    err,
                    msg: '服务器异常',
                    type: 0
                })
            })
    })
})

// 上传头像
const multer = require('multer');  // 上传文件需要用到的插件
var storage = multer.diskStorage({   // diskStorage 硬盘存储 
    destination: function (req, file, cb) {
      cb(null, './public/avatar')    // 文件路径 
    },
    filename: function (req, file, cb) {  // 文件名 
        cb(null, Date.now() + "ymt" + file.originalname)  // file.originalname 文件的原始名字
    }
})
var upload = multer({ storage: storage }).any()  // any 不限定文件 数量

router.post('/mzsendavatar', upload, (req, res) => {
    checkToken(req, res, ({
        phone, username
    }) => {
        console.log(req.fils);
        const path = req.files[0].path;
        MaizuoUsersModel.updateMany({
            $or: [{ phone }, { username }]
        }, {
            $set: {
                avatar: path
            }
        })
            .then(result => {
                console.log(result, 1212);
                res.json({
                    code: 200,
                    msg: '上传成功',
                    avatar: path,
                    type: 1,
                    result
                })
            })
            .catch(err => {
                console.log(err);
                res.json({
                    code: 500,
                    err,
                    msg: '服务器异常',
                    type: 0
                })
            })
        
    })
})


module.exports = router;